package org.com.blbl.School;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.*;

public class SchoolReducer extends Reducer<Text,IntWritable,Text,IntWritable>{

    private Map<String, Integer>countMap = new HashMap<>();

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        int count = 0;
        // 计算每个学校的总数量
        for (IntWritable val : values) {
            count += val.get();
        }
        countMap.put(key.toString(), count);
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        // 对学校进行排序
        List<Map.Entry<String, Integer>> list = new ArrayList<>(countMap.entrySet());
        list.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue())); // 降序排序

        // 输出排名
        int rank = 1;
        for (Map.Entry<String, Integer> entry : list) {
            context.write(new Text(rank + ". " + entry.getKey()), new IntWritable(entry.getValue()));
            rank++;
        }
    }
}
